<?php get_header();

//Get link query vars ------------------------


$orderby = delinks_get_orderby();
$orderdir = delinks_get_orderdir();



$uripath = preg_replace('#/tag/[^/]+/?#', '/', parse_url($_SERVER['REQUEST_URI'], PHP_URL_PATH));
?>
<?php the_post(); ?>
<article id="content" class='directory'>
	<header><h2><?php 
	
	$tags = get_query_var('delicious_tags');
	if(!empty($tags)){
		print "<a rel='up' href='" . get_permalink() . "'>" . get_the_title() . "</a>: ";
		#print " &gt; ";
		$tagLinks = array();
		foreach($tags as $tag)
			$tagLinks[] = "<a rel='tag' href='{$uripath}tag/" . htmlspecialchars($tag) . "/'>" . htmlspecialchars($tag) . "</a>";
		print join(' + ', $tagLinks);
	}
	else {
		the_title();
	}
	?>
	</h2>
	</header>

	<?php
	$taginfo = delinks_get_tags();
	
	if(!get_query_var('delicious_tags'))
		the_content();
	
	
	//Tag cloud
	if(count($taginfo) > 1){
		print "<section id='tagcloud'><h3 title='Tags are provided by users on Delicious'><a href='http://delicious.com/' target='_blank'>Delicious</a> Tags</h3>";
		
		$maxCount = null;
		$minCount = null;
		foreach($taginfo as $tag){
			if(is_null($maxCount) || $tag->link_count > $maxCount)
				$maxCount = $tag->link_count;
			if(is_null($minCount) || $tag->link_count < $minCount)
				$minCount = $tag->link_count;
		}
		
		$maxFontSize = 90;
		$minFontSize = 12;
		$minGreyColor = 150;
		
		//Slopes of the line for calculating the font size and color
		$mFontSize = (float)($maxFontSize - $minFontSize)/$maxCount;
		$mColor = (float)(-$minGreyColor)/$maxCount;
		
		foreach($taginfo as $tag){
			$fontSize = $mFontSize*$tag->link_count + $minFontSize;
			$hex = dechex(round($mColor*$tag->link_count + $minGreyColor));
			if(strlen($hex) == 1)
				$hex = "0$hex";
			$color = '#' . str_repeat($hex, 3);
			#$color = '#' . str_repeat(dechex(round($mColor*$tag->link_count + $minGreyColor)), 3);
			
			print " <a rel='tag' title='" . htmlspecialchars($tag->tag) . " ($tag->link_count)' href='" . $uripath . 'tag/' . htmlspecialchars($tag->tag) . "/' style='font-size:{$fontSize}px; color:$color; '>";
			print htmlspecialchars($tag->tag);
			print "</a>";
			print " ";
		}
		
		print "</section>";
	}
	
	//Link query ------------------------------------------------------------
	$links = get_delinks();
	if(empty($links)){
		print "<p><em>No links available with this tag.</em></p>";
	}
	else {
		//Sort by links ------------------------------------------------
		if(get_query_var('delicious_tags')){
			print "<p id='linksorting'>Sort by: ";
			$orderlinks = array();
			foreach($delinks_ordering_info as $orderkey => $orderinfo){
				$newOrderdir = $orderinfo['orderdir'];
				
				$link = '';
				if($orderby == $orderkey){
					$link .= '<strong>';
					$newOrderdir = ($orderdir == 'asc' ? 'desc' : 'asc');
				}
				$link .= "<a href='" . parse_url($_SERVER['REQUEST_URI'], PHP_URL_PATH) . "?orderby=$orderkey&amp;orderdir=$newOrderdir#content' title='" . htmlspecialchars("Sort by " . strtolower($orderinfo['name']) . ' ' . ($newOrderdir == 'asc' ? 'ascending' : 'descending')) . "'>";
				$link .= htmlspecialchars($orderinfo['name']);
				$link .= "</a>";
				if($orderby == $orderkey){
					$link .= '</strong>';
					$link .= ($orderdir == 'asc' ? "▲" : "▼");
				}
				$orderlinks[] = $link;
			}
			print join(' | ', $orderlinks);
			print "</p>";
		}
		else {
			print "<p><em>Recently added links:</em></p>";
		}
		
		$maxPopularity = -1;
		foreach($links as $link){
			$maxPopularity = max($maxPopularity, $link->post_count);
		}
		$mPopularity = (float)(100)/$maxPopularity;
		
		
		print "<ol>";
		foreach($links as $link){
			print "<li style='";
			print "'>";
			print "<h4><a style='";
			print "' href='" .  htmlspecialchars($link->link_url) . "' rel='" . $link->link_rel . "'>" . apply_filters('the_title', $link->link_name) . "</a></h4>";
			$linkTags = delinks_get_link_tags($link->link_id);
			if(count($linkTags)){
				print "<p class='tags'>Tags: ";
				
				$maxTagCount = 0;
				foreach($linkTags as $taginfo){
					$maxTagCount = max($maxTagCount, $taginfo->count);
				}
				
				$minGreyColor = 200;
				$mColor = (float)(-$minGreyColor)/$maxTagCount;
				
				$linkTagsEls = array();
				foreach( $linkTags as $taginfo){
					#$linkTagsEls[] = "round($mColor*$count + $minGreyColor)=".round($mColor*$count + $minGreyColor).'='.str_repeat(dechex(round($mColor*$count + $minGreyColor)), 3);
					$hex = dechex(round($mColor*$taginfo->count + $minGreyColor));
					if(strlen($hex) == 1)
						$hex = "0$hex";
					$color = '#' . str_repeat($hex, 3);
					$a = "<a href='{$uripath}tag/" . htmlspecialchars($taginfo->tag) . "/' style='color:$color' rel='tag'>$taginfo->tag</a>"; # title='" . htmlspecialchars($taginfo->tag) . " ($taginfo->count)'
					if(in_array($taginfo->tag, (array)get_query_var('delicious_tags')))
						$a = "<strong>$a</strong>";
					$linkTagsEls[] = $a;
				}
				print join(', ', $linkTagsEls);
				print "</p>";
			}
			
			$users = delinks_get_link_owners($link->link_id);
			if($link->link_description){
				print apply_filters('the_content', $link->link_description);
			}
			
			if(!empty($users)){
				print "<p class='contributors'>Contributors: ";
				$userLinks = array();
				foreach($users as $user){
					$userLink = '';
					if($user->user_url && $user->user_url != 'http://')
						$userLink .= "<a href='" . htmlspecialchars($user->user_url) . "' target='_blank'>";
					$userLink .= "<img alt='Gravatar for " . htmlspecialchars($user->display_name) . "' src='" . htmlspecialchars("http://www.gravatar.com/avatar/" . md5(strtolower($user->user_email)) . ".jpg?s=16&d=identicon") . "' />";
					
					$userLink .= htmlspecialchars($user->display_name);
					if($user->user_url && $user->user_url != 'http://')
						$userLink .= '</a>';
					$userLinks[] = $userLink;
				}
				print join(', ', $userLinks);
				print "</p>";
			}
			if($link->post_count){
				$borderWidth = ceil($mPopularity*$link->post_count);
				print "<span class='post_count' style='border-right-width:{$borderWidth}px;' title='This resource has been posted on Delicious " . ($link->post_count == 1 ? 'once' : $link->post_count . ' times') . "'>$link->post_count</span> ";
			}
			print "</li>";
		}
		print "</ol>";
	}
	//edit_post_link('Edit page', '<p>[', ']</p>');
	?>
	<section id='link_suggest'>
		<h3>Suggest a Link</h3>
		<?php if(is_user_logged_in()): ?>
			<p>All links listed in this directory are for open projects; no proprietary/closed resources may be listed. Before suggesting a link, first check to see if it makes data or code available
			under an <a href="http://en.wikipedia.org/wiki/Open_source_license" target="_blank">open source</a> or <a href="http://creativecommons.org/licenses/" target="_blank">Creative Commons</a> license.</p>
			
			<form method="post" action="<?php echo $_SERVER['REQUEST_URI'] ?>#link_suggest">
				<?php
				if($_SERVER['REQUEST_METHOD'] == 'POST'){
					if(get_magic_quotes_gpc()){
						$_POST['oss_link_name'] = stripslashes(@$_POST['oss_link_name']);
						$_POST['oss_link_url'] = stripslashes(@$_POST['oss_link_url']);
						$_POST['oss_link_description'] = stripslashes(@$_POST['oss_link_description']);
					}
					
					if(!empty($_POST['oss_link_name']) && !empty($_POST['oss_link_url'])){
						$_POST['oss_link_url'] = trim($_POST['oss_link_url']);
						
						if(!preg_match('#^https?://.+#', $_POST['oss_link_url'])){
							print "<p style='color:red'><em>Your URL does not appear to be formatted properly.</em></p>";
						}
						else if($wpdb->get_var( $wpdb->prepare("SELECT count(*) FROM $wpdb->links WHERE link_url = %s", $_POST['oss_link_url']) )){
							print "<p style='color:red'><em>The URL you submitted has already been suggested.</em></p>";
						}
						else {
							get_currentuserinfo();
							global $current_user;
							$res = $wpdb->query($wpdb->prepare( "INSERT INTO $wpdb->links (link_name, link_url, link_description, link_visible, link_notes) VALUES (%s, %s, %s, %s, %s)",
															$_POST['oss_link_name'],
															$_POST['oss_link_url'],
															$_POST['oss_link_description'],
															'N',
															"Submitted by $current_user->user_login"
							));
							if($res === false)
								print "<p style='color:red'><em>There was an error with your submission.</em></p>";
							else { 
								print "<p style='color:green'><strong><em>Thank you for your suggestion. Your suggestion will appear pending approval.</em></strong></p>";
								
								#Send mail alerting
								$message = '';
								$message .= "Name: $_POST[oss_link_name]\n";
								$message .= "URL: $_POST[oss_link_url]\n";
								$message .= "Description:\n$_POST[oss_link_description]\n";
								$message .= "\nModerate: http://openscriptures.org/wp-admin/link.php?action=edit&link_id=$wpdb->insert_id";
								@wp_mail(get_option('admin_email'), "OSS Directory Suggestion: " . $_POST['oss_link_name'], $message, "From: \"$current_user->user_login\" <$current_user->user_email>");
								
								$_POST['oss_link_name'] = $_POST['oss_link_url'] = $_POST['oss_link_description'] = '';
							}
						}
					}
					else {
						print "<p style='color:red'><em>You must provide both the link name and URL.</em></p>";
					}
				}
				?>
				<p><label for="oss_link_name">Link Name: </label><input type="text" required="required" id="oss_link_name" name="oss_link_name" value="<?php echo htmlspecialchars(@$_POST['oss_link_name']) ?>" /></p>
				<p><label for="oss_link_url">Link URL: </label><input type="url" required="required" id="oss_link_url" name="oss_link_url" value="<?php echo htmlspecialchars(empty($_POST['oss_link_url']) ? 'http://' : @$_POST['oss_link_url']) ?>" /></p>
				<p><label for="oss_link_description">Description: <small>(optional; 255 chars)</small></label><textarea id="oss_link_description" maxlength="255" name="oss_link_description"><?php
				echo htmlspecialchars(@$_POST['oss_link_description']);
				?></textarea></p>
				<button type="submit">Submit</button>
			</form>
		<?php else: ?>
			<p><em>You must be a registered user to suggest a link. <a rel="nofollow" href="/wp-login.php?redirect_to=<?php echo urlencode('http://' . $_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI'] . '#link_suggest') ?>">Log in</a> or <?php wp_register('', '') ?>.</em></p>
		<?php endif; ?>
	</section>
	<?php comments_template(); ?>
</article>

<?php get_sidebar(); ?>
<?php get_footer(); ?>
